package com.hankai.service.impl;

import com.hankai.common.Const;
import com.hankai.common.ServerResponse;
import com.hankai.common.TokenCache;
import com.hankai.dao.UserMapper;
import com.hankai.pojo.User;
import com.hankai.service.IUserService;
import com.hankai.util.MD5Util;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.weaver.patterns.TypePatternQuestions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.UUID;

/**
 * Created by hankai on 2017/6/3.
 */
@Service
public class UserServiceImpl implements IUserService {
    @Resource
    private UserMapper userMapper;

    @Override
    public ServerResponse<User> login(String username, String password) {
        password = MD5Util.MD5EncodeUtf8(password);
        if (userMapper.checkUsername(username) == 0) {
            return ServerResponse.createByError("用户名不存在");
        }

        User user = userMapper.selectLogin(username, password);
        if (user == null) {
            return ServerResponse.createByError("你输入的密码不正确");
        }
        user.setPassword(StringUtils.EMPTY);
        return ServerResponse.createBySuccess("登陆成功", user);
    }

    @Override
    public ServerResponse<String> register(User user) {

        ServerResponse<String> server = this.checkValid(user.getUsername(), Const.USERNAME);
        if (!server.isSuccess()) {
            return server;
        }
        server = this.checkValid(user.getEmail(), Const.EMAIL);
        if (!server.isSuccess()) {
            return server;
        }
        user.setRole(Const.Role.ROLE_CUSTOMER);//注册用户为普通员工
        user.setPassword(MD5Util.MD5EncodeUtf8(user.getPassword()));
        if (userMapper.insert(user) == 0) {
            return ServerResponse.createByError("注册失败");
        }
        return ServerResponse.createBySuccess();
    }

    @Override
    public ServerResponse<String> checkValid(String str, String type) {
        if (StringUtils.isNoneBlank(type)) {//类型不为空
            //开始校验
            if (type.equals(Const.USERNAME)) {
                if (userMapper.checkUsername(str) > 0) {
                    return ServerResponse.createByError("用户名已存在");
                }
            } else if (type.equals(Const.EMAIL)) {
                if (userMapper.checkEmail(str) > 0) {
                    return ServerResponse.createByError("邮箱已存在");
                }
            }
        } else {
            return ServerResponse.createByError("类型为空");
        }
        return ServerResponse.createBySuccess("验证成功");
    }

    public ServerResponse<String> forGetQuestion(String username) {
        ServerResponse server = this.checkValid(username, Const.USERNAME);
        if (server.isSuccess()) {
            return ServerResponse.createByError("用户名不存在");
        }

        String quertion = userMapper.getQuertionByUsername(username);
        if (StringUtils.isNoneBlank(quertion)) {
            return ServerResponse.createBySuccess(quertion);
        }
        return ServerResponse.createByError("问题为空");
    }

    public ServerResponse<String> checkAnswer(String username, String question, String answer) {
        int count = userMapper.checkAnswer(username, question, answer);
        if(count>0){
            String token = UUID.randomUUID().toString();
            TokenCache.setKey("token_"+username,token);
            return ServerResponse.createBySuccess(token);
        }
        return ServerResponse.createByError("问题回答错误");
    }

    @Override
    public ServerResponse<String> resetPassword(String password, String newPassword, User user) {
        int result = userMapper.checkPassword(MD5Util.MD5EncodeUtf8(password),user.getId());
        if(result==0){
            return ServerResponse.createByError("原始密码输入有误！");
        }
        user.setPassword(MD5Util.MD5EncodeUtf8(newPassword));
        result = userMapper.updateByPrimaryKeySelective(user);
        if(result==0){
            return ServerResponse.createByError("密码修改失败，未知错误，请重新输入");
        }
        return ServerResponse.createBySuccess("密码修改成功");
    }

    @Override
    public ServerResponse<User> updateInformation(User user) {
        user.setUsername(null);//不能修改用户名
        //判断别的用户是否使用这个email
        int result = userMapper.checkEmailById(user.getEmail(),user.getId());
        if(result>0){
            return ServerResponse.createByError("此email已经被使用");
        }
        result = userMapper.updateByPrimaryKeySelective(user);
        if(result==0){
            return ServerResponse.createByError("修改失败");
        }
        return ServerResponse.createBySuccess("修改成功",user);
    }

    @Override
    public ServerResponse<User> getInfoMation(Integer id) {
        User user = userMapper.selectByPrimaryKey(id);
        if(user==null){
            return ServerResponse.createByError("获取用户列表失败");
        }
        user.setPassword(StringUtils.EMPTY);
        return ServerResponse.createBySuccess(user);

    }

    @Override
    public ServerResponse checkIsNotAdmin(User user) {
        if(user.getRole().equals(Const.Role.ROLE_ADMIN)){
            return ServerResponse.createBySuccess();
        }
        return ServerResponse.createByError("你不是管理员权限");
    }
}
